<?php
/**
 * Introduction: 订单表  order
 */

namespace Common\Model;


use Think\Model;
use Think\Wxpay\Wxpush;

class OrderModel extends Model
{
    //定义数据库连接信息
    protected $connection;

    //定义表名
    protected $tableName = 'order';

    /**
     * 初始化
     */
    public function _initialize()
    {

        $this->connection = C('Databaese');

    }

    /**
     * 我的订单列表
     */
    public function order_list($member_id,$num,$limit,$status){
        //0:取消订单 1:已下单，未支付 2：已支付 3：已发货 4：已完成
        $where = "";
        if($status!=5){
            $where .=" and status=$status";
        }else{
            $where .= ' and  (status=1 and separate_status=1)';
        }
        $order_list = $this->where("member_id=$member_id and separate_status<=0  $where")->order("create_time desc")->field("id,order_id,create_time,status,cost,cash_price,total_ms_taxation,ms_freight_risk,freight,cpns_price,shipping_express_name")->limit($num,$limit)->select();
        $model = new OrderProductModel();
        foreach($order_list as $k=>$v){
            $total_price = 0;
            $total_price += floatval($v['cost'])-floatval($v['cpns_price'])+floatval($v['freight'])+floatval($v['ms_freight_risk'])+floatval($v['total_ms_taxation']);
            $order_list[$k]['total_price'] = $total_price;
            $product_list = $model->alias('op')->join("left join haiou_stock_shops as s on s.id=op.stock_shop")->where("op.order_id='".$v['order_id']."'")->field('op.*,s.title as stock_shop_title')->select();
            $order_list[$k]['product_list'] = $product_list;
        }
        return $order_list;
    }

    /**
     * 订单详情
     */
    public function order_details($member_id,$order_id){
        $order_info = $this->where("member_id=$member_id and order_id=$order_id")->field("id,order_id,create_time,status,cost,cash_price,total_ms_taxation,ms_freight_risk,freight,cpns_price,ship_name,ship_mobile,ship_addr")->find();
        if($order_info){
            $model = new OrderProductModel();
            $total_price = 0;
            $total_price += floatval($order_info['cost'])-floatval($order_info['cpns_price'])+floatval($order_info['freight'])+floatval($order_info['ms_freight_risk'])+floatval($order_info['total_ms_taxation']);
            $order_info['total_price'] = $total_price;
            $product_list = $model->alias('op')->join("left join haiou_stock_shops as s on s.id=op.stock_shop")->where("op.order_id=".$order_info['order_id'])->field('op.*,s.title as stock_shop_title')->select();
            $order_info['product_list'] = $product_list;
        }
        return $order_info;
    }

    /**
     * 确认收货
     */
    public function confirm_receipt($member_id,$order_id){
        $order_info = $this->where("member_id=$member_id and order_id=$order_id")->field('status')->find();
        if($order_info['status']!=3){
            return ['code'=>300,'msg'=>'您好，此订单还未发货，不能收货'];
        }
        $result = $this->where("member_id=$member_id and order_id=$order_id")->save(['status'=>4]);
        if($result){
            return ['code'=>200,'msg'=>'确认收货成功'];
        }else{
            return ['code'=>300,'msg'=>'确认收货失败，请稍后再试'];
        }
    }

    /**
     * 支付成功查看订单是否有多个订单(并修改)
     */
    public function order_see($order_id){
        $data['status'] = 2;
        $data['pay_status'] = 2;
        $data['pay_time']  = time();
        $this->where("order_id=$order_id")->save($data);
        $orderLogModel = new OrderLogModel();
        $orderLogModel->insertOneLog($order_id,'订单付款完成','付款');
        $list = $this->where("master_order_id=$order_id")->select();  //查看是否有子订单
        if($list){
            foreach($list as $v){
                $orderLogModel->insertOneLog($v['order_id'],'订单付款完成','付款');
                $this->where("order_id=".$v['order_id'])->save($data);
            }
        }
        $order_info = $this->where("order_id=$order_id")->find();
        $ms_id = $order_info['ms_id']; //店铺id

        if($ms_id>0){//微店订单，加销售额
            $this->updateSaleInfoAndGiveBonus($order_id);
        }

    }

    /**
     * 更新微店销售额和发红包
     * @param unknown $oid
     */
    public function updateSaleInfoAndGiveBonus($oid){
        global $config;
        $de = $this->where("order_id=$oid")->field("order_id,ms_id,member_id,status,cost,discount,cpns_price,cash_price,freight,stock_shop,shipping_name,shipping_no,ship_addr,ship_name,separate_status")->find();
        //给用户推送消息
        $replaceArr = [];
        //订单商品信息
        $model = new OrderProductModel();
        $order_p = $model->where("order_id=$oid")->field("product_name")->find();
        $param = [
            'memberId'=>$de['member_id'],
            'orderProductPrice'=>$config['money'].' '.$de['cost'],
            'orderProductName'=>$order_p['product_name'],
            'orderAddress'=>$de['ship_name'].','.$de['ship_addr'],
            'orderName'=>$oid,
            'url'=>'http://wx.52ywy.com/?shop='.$de['ms_id'].'#&cart/orderdetail/?id='.$oid
        ];


        $Wxpush = new Wxpush();
        $message = $Wxpush->getMessageDetail('orderPaySuccess', $replaceArr, $param);

        if(!empty($message)){//调用接口
            $param['first'] = $message['subject'];
            $param['remark'] = $message['message'];

            $result = $Wxpush->msgPush($param['memberId'], 'orderPaySuccess', $param);
            //写日志
            $data['param'] = ["memberId"=>$param['memberId'],"msgType"=>'orderPaySuccess',"msgInfo"=>$param];
            $data['result'] = $result;
            $datas = json_encode($data,JSON_UNESCAPED_UNICODE);
            $datas = @mysql_escape_string($datas);
            $modes_log = new GeneralLogModel();
            $modes_log->add(['type'=>'PUSH_WX_MSG','data'=>$datas,'status'=>1]);
        }
        $microShop = new MicroShopModel();
        $microShop->updateSalesInfoByOrder($oid);//更新销售额

        //发红包
        $microShop->giveOutBonusOfOrder($oid);
    }


    /**
     * 获取未收益订单列表信息
     * @param unknown $orderIds
     */
    public function getWaitingEarnOrdersByOrderIds($orderIds)
    {

        $fields = ['a.order_id','a.ms_id','a.ship_name','a.create_time','a.cost','a.cpns_price','a.freight','a.cash_price','a.status','a.stock_shop','b.logo','b.name','a.shipping_express_name'];
        $order_id = join(',',$orderIds);
        $list =  $this->alias('a')->join("left join haiou_member as b on a.member_id=b.userid")->where("order_id in ($order_id)")->order("pay_time desc")->field($fields)->select();
        //关联订单商品
        $model = new OrderProductModel();
        foreach($list as $k=>$v){
            $fields = ['a.order_id','a.product_id', 'a.product_name', 'a.property', 'a.num', 'a.pic', 'a.price','c.title','c.show_title','c.country_en'];
            $product_list = $model->alias('a')->join("left join haiou_product_sku as b on b.id=a.product_id left join haiou_stock_shops as c on b.stock_shop=c.id")->where("order_id=".$v['order_id'])->field($fields)->select();
            $list[$k]['product_list'] = $product_list;
        }

        return $list;
    }

    /**
     * 获取未收益订单详细信息
     * @param unknown $orderIds
     */
    public function getWaitingEarnOrdersByOrderId($order_id)
    {

        $fields = ['a.tax_price','a.order_id','a.ms_id','a.ship_name','a.create_time','a.cost','a.cpns_price','a.freight','a.cash_price','a.status','a.stock_shop','b.logo','b.name'];
        $list =  $this->alias('a')->join("left join haiou_member as b on a.member_id=b.userid")->where("order_id = $order_id")->order("pay_time desc")->field($fields)->find();
        //关联订单商品
        $model = new OrderProductModel();
        $fields = ['a.order_id','a.product_id', 'a.product_name', 'a.property', 'a.num', 'a.pic', 'a.price','c.title','c.show_title','c.country_en','b.spec'];
        $product_list = $model->alias('a')->join("left join haiou_product_sku as b on b.id=a.product_id left join haiou_stock_shops as c on b.stock_shop=c.id")->where("order_id=".$list['order_id'])->field($fields)->select();
        $list['product_list'] = $product_list;


        return $list;
    }

    /**
     * 获取已支付订单数量，通过店铺范围，日期条件
     * @param array $shopsId 店铺ID
     * @param string $dateStart 开始时间：null 没有开始时间
     * @param string $dateEnd 结束时间： null - 没有结束时间
     * @return int
     */
    public function getPaidNumByWithDateWithShops($shopsId)
    {
        if (empty($shopsId)) {
            return 0;
        }
        return $this->where("ms_id=$shopsId and status>=2")->count();
    }

}